/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#pragma once

#include "velox/type/SimpleFunctionApi.h"
#include "velox/type/Type.h"

namespace facebook::velox {

class TDigestType final : public VarbinaryType {
 public:
  static std::shared_ptr<const TDigestType> get(const TypePtr& dataType) {
    // Only TDIGEST(DOUBLE) exists in Presto so we use a singleton to improve
    // performance.
    VELOX_CHECK(dataType->isDouble());
    static const TDigestType kInstance{DOUBLE()};
    return {std::shared_ptr<const TDigestType>{}, &kInstance};
  }

  bool equivalent(const Type& other) const override {
    // Pointer comparison works since this type is a singleton.
    return this == &other;
  }

  const char* name() const override {
    return "TDIGEST";
  }

  std::span<const TypeParameter> parameters() const override {
    return {&parameter_, 1};
  }

  std::string toString() const override {
    return fmt::format("TDIGEST({})", parameter_.type->toString());
  }

  folly::dynamic serialize() const override {
    folly::dynamic obj = folly::dynamic::object;
    obj["name"] = "Type";
    obj["type"] = name();
    folly::dynamic children = folly::dynamic::array;
    children.push_back(parameter_.type->serialize());
    obj["cTypes"] = children;
    return obj;
  }

  bool isOrderable() const override {
    return false;
  }

 private:
  explicit TDigestType(const TypePtr& dataType) : parameter_(dataType) {}

  const TypeParameter parameter_;
};

inline bool isTDigestType(const TypePtr& type) {
  // Pointer comparison works since this type is a singleton.
  return TDigestType::get(DOUBLE()) == type;
}

inline std::shared_ptr<const TDigestType> TDIGEST(const TypePtr& dataType) {
  return TDigestType::get(dataType);
}

// Type to use for inputs and outputs of simple functions, e.g.
// arg_type<TDigest> and out_type<TDigest>.
template <typename T>
struct SimpleTDigestT;

template <>
struct SimpleTDigestT<double> {
  using type = Varbinary;
  static constexpr const char* typeName = "tdigest(double)";
};

template <typename T>
using SimpleTDigest = CustomType<SimpleTDigestT<T>>;

} // namespace facebook::velox
